import * as echarts from 'echarts';

var chartDom = document.getElementById('main');
var myChart = echarts.init(chartDom);
var option;

const symbolSize = 14;
const targetMonth = '2025-03'; // 可动态指定月份

// 生成当月的所有日期
function getAllDates(monthStr) {
  const dates = [];
  const date = new Date(`${monthStr}-01`);
  const year = date.getFullYear();
  const month = date.getMonth();
  const lastDay = new Date(year, month + 1, 0).getDate();

  for (let i = 1; i <= lastDay; i++) {
    const d = new Date(year, month, i);
    const dateStr = d.toISOString().split('T')[0];
    dates.push(dateStr);
  }
  return dates;
}

const dateLabels = getAllDates(targetMonth);
const data = dateLabels.map((d) => [d, 10000]); // 初始值设为 10000

option = {
  title: {
    text: `${targetMonth} 每日目标调整`,
    left: 'center'
  },
  tooltip: {
    triggerOn: 'none',
    formatter: function (params) {
      return `日期：${params.data[0]}<br>目标值：￥${params.data[1].toFixed(
        2
      )}`;
    }
  },
  grid: {
    top: '10%',
    bottom: '15%'
  },
  xAxis: {
    type: 'category',
    data: dateLabels,
    name: '日期',
    axisLabel: {
      rotate: 45,
      formatter: (val) => val.slice(5) // 显示为 MM-DD
    }
  },
  yAxis: {
    min: 0,
    max: 30000,
    type: 'value',
    name: '目标值（元）'
  },
  dataZoom: [
    {
      type: 'slider',
      xAxisIndex: 0,
      start: 0,
      end: 100
    },
    {
      type: 'inside',
      xAxisIndex: 0
    }
  ],
  series: [
    {
      id: 'a',
      type: 'line',
      smooth: false,
      symbolSize: symbolSize,
      data: data
    }
  ]
};

// 拖拽控制器
setTimeout(function () {
  myChart.setOption({
    graphic: data.map(function (item, dataIndex) {
      return {
        type: 'circle',
        position: myChart.convertToPixel('grid', item),
        shape: {
          cx: 0,
          cy: 0,
          r: symbolSize / 2
        },
        invisible: true,
        draggable: true,
        ondrag: function () {
          onPointDragging(dataIndex, [this.x, this.y]);
        },
        onmousemove: function () {
          showTooltip(dataIndex);
        },
        onmouseout: function () {
          hideTooltip(dataIndex);
        },
        z: 100
      };
    })
  });
}, 0);

window.addEventListener('resize', updatePosition);
myChart.on('dataZoom', updatePosition);

function updatePosition() {
  myChart.setOption({
    graphic: data.map(function (item) {
      return {
        position: myChart.convertToPixel('grid', item)
      };
    })
  });
}

function showTooltip(dataIndex) {
  myChart.dispatchAction({
    type: 'showTip',
    seriesIndex: 0,
    dataIndex: dataIndex
  });
}

function hideTooltip(dataIndex) {
  myChart.dispatchAction({
    type: 'hideTip'
  });
}

function onPointDragging(dataIndex, pos) {
  const originalDate = data[dataIndex][0]; // 保持 X 日期不变
  const coord = myChart.convertFromPixel('grid', pos);
  const newY = coord[1];
  data[dataIndex] = [originalDate, newY];

  myChart.setOption({
    series: [
      {
        id: 'a',
        data: data
      }
    ]
  });

  updatePosition();
}

option && myChart.setOption(option);
